#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
评价处理器
负责处理各类评价题型的逻辑
"""

import random
import logging
from typing import Dict, Any, List, Optional

logger = logging.getLogger(__name__)

class EvaluationEngine:
    """
    评价引擎，处理不同类型的评价题目
    """
    
    def __init__(self, api_client, retry_handler, probabilities_config):
        """
        初始化评价引擎
        
        Args:
            api_client: API客户端，用于调用豆包模型
            retry_handler: 重试机制处理器
            probabilities_config: 各题型评分概率配置
        """
        self.api_client = api_client
        self.retry_handler = retry_handler
        self.probabilities = probabilities_config
        self.browser = None  # 实际项目中需要传入浏览器控制实例
    
    def set_browser(self, browser):
        """设置浏览器实例"""
        self.browser = browser
    
    def handle_choice_question(self, question_id: str = None) -> Dict[str, Any]:
        """
        处理选择题类型的评价
        
        Args:
            question_id: 题目ID，可选
            
        Returns:
            Dict: 操作结果状态信息
        """
        logger.info(f"开始处理选择题，题目ID: {question_id or '未指定'}")
        
        try:
            # 1. 识别当前题目类型（如满意度、教学质量等）
            question_type = self._detect_question_type()
            
            # 2. 获取当前题目的选项列表
            options = self._get_question_options()
            
            # 3. 根据概率配置选择选项
            selected_option = self._select_option_by_probability(question_type, options)
            
            # 4. 点击选中的选项
            self._click_option(selected_option)
            
            # 5. 生成操作轨迹日志
            operation_log = {
                "question_id": question_id or "unknown",
                "question_type": question_type,
                "options": options,
                "selected": selected_option,
                "timestamp": self._get_timestamp()
            }
            
            logger.info(f"选择题处理完成: {operation_log}")
            return {"status": "success", "operation": operation_log}
            
        except Exception as e:
            logger.error(f"处理选择题时发生异常: {e}")
            return {"status": "error", "message": str(e)}
    
    def handle_text_question(self, question_id: str = None, model_version: str = "v2") -> Dict[str, Any]:
        """
        处理填空题类型的评价
        
        Args:
            question_id: 题目ID，可选
            model_version: 豆包模型版本号
            
        Returns:
            Dict: 操作结果状态信息
        """
        logger.info(f"开始处理填空题，题目ID: {question_id or '未指定'}")
        
        try:
            # 1. 获取题目内容
            question_text = self._get_question_text()
            
            # 2. 调用豆包模型生成回答
            max_retries = 3
            current_try = 0
            
            while current_try < max_retries:
                try:
                    answer = self.api_client.generate_answer(
                        question=question_text,
                        model_version=model_version
                    )
                    
                    # 3. 验证返回文本有效性
                    if self._validate_answer(answer, question_text):
                        break
                    
                    current_try += 1
                    logger.warning(f"生成的回答无效，尝试重新生成 ({current_try}/{max_retries})")
                
                except Exception as e:
                    # 4. 失败时触发retry_mechanism
                    current_try += 1
                    logger.error(f"生成回答失败: {e}, 尝试重试 ({current_try}/{max_retries})")
                    
                    # 使用重试机制
                    self.retry_handler.handle_failure(
                        operation="generate_answer",
                        error=str(e),
                        attempt=current_try,
                        max_attempts=max_retries
                    )
            
            if current_try >= max_retries:
                logger.error("填空题回答生成失败，达到最大重试次数")
                return {"status": "error", "message": "达到最大重试次数"}
            
            # 5. 填写回答到文本框
            self._fill_answer(answer)
            
            # 6. 生成操作轨迹日志
            operation_log = {
                "question_id": question_id or "unknown",
                "question_text": question_text,
                "answer": answer,
                "model_version": model_version,
                "retries": current_try,
                "timestamp": self._get_timestamp()
            }
            
            logger.info(f"填空题处理完成: {operation_log}")
            return {"status": "success", "operation": operation_log}
            
        except Exception as e:
            logger.error(f"处理填空题时发生异常: {e}")
            return {"status": "error", "message": str(e)}
    
    def _detect_question_type(self) -> str:
        """
        识别当前问题的类型
        
        Returns:
            str: 问题类型（如"teaching_quality", "course_content"等）
        """
        # 实际实现时需根据界面元素判断
        # 这里仅作示例
        try:
            # 通过XPath或其他方式识别问题类型
            question_container = self.browser.find_element_by_xpath("//div[contains(@class, 'question-container')]")
            question_text = question_container.text.lower()
            
            # 根据关键词判断问题类型
            if "教学质量" in question_text or "teaching quality" in question_text:
                return "teaching_quality"
            elif "课程内容" in question_text or "course content" in question_text:
                return "course_content"
            elif "师生互动" in question_text or "interaction" in question_text:
                return "teacher_interaction"
            else:
                return "general_satisfaction"
                
        except Exception:
            return "general_satisfaction"  # 默认类型
    
    def _get_question_options(self) -> List[str]:
        """
        获取当前问题的选项列表
        
        Returns:
            List[str]: 选项文本列表
        """
        # 实际实现时需根据界面元素获取
        # 这里仅作示例
        options = []
        try:
            option_elements = self.browser.find_elements_by_xpath("//div[contains(@class, 'option')]")
            for element in option_elements:
                options.append(element.text.strip())
        except Exception as e:
            logger.error(f"获取选项列表失败: {e}")
            # 默认选项
            options = ["非常满意", "满意", "一般", "不满意", "非常不满意"]
        
        return options
    
    def _select_option_by_probability(self, question_type: str, options: List[str]) -> str:
        """
        根据概率配置选择选项
        
        Args:
            question_type: 问题类型
            options: 可选选项列表
            
        Returns:
            str: 选中的选项文本
        """
        # 获取当前问题类型的概率分布
        probability_dist = self.probabilities.get(question_type, {
            "satisfied": 0.7,
            "neutral": 0.2,
            "unsatisfied": 0.1
        })
        
        # 根据概率生成选择倾向
        rand = random.random()
        if rand < probability_dist["satisfied"]:
            # 选择满意类选项（通常是前两个选项）
            return options[0] if len(options) > 0 else "非常满意"
        elif rand < probability_dist["satisfied"] + probability_dist["neutral"]:
            # 选择中立选项（通常是中间选项）
            middle_idx = len(options) // 2
            return options[middle_idx] if len(options) > middle_idx else "一般"
        else:
            # 选择不满意选项（通常是后两个选项）
            return options[-1] if len(options) > 0 else "不满意"
    
    def _click_option(self, option_text: str) -> bool:
        """
        点击指定文本的选项
        
        Args:
            option_text: 选项文本
            
        Returns:
            bool: 点击操作是否成功
        """
        try:
            # 构造XPath，查找包含指定文本的选项元素
            xpath = f"//div[contains(@class, 'option') and contains(text(), '{option_text}')]"
            option_element = self.browser.find_element_by_xpath(xpath)
            option_element.click()
            logger.info(f"成功点击选项: {option_text}")
            return True
        except Exception as e:
            logger.error(f"点击选项失败: {option_text}, 错误: {e}")
            return False
    
    def _get_question_text(self) -> str:
        """
        获取当前问题的文本内容
        
        Returns:
            str: 问题文本
        """
        try:
            question_element = self.browser.find_element_by_xpath("//div[contains(@class, 'question-text')]")
            return question_element.text.strip()
        except Exception as e:
            logger.error(f"获取问题文本失败: {e}")
            return "请对本课程进行评价"  # 默认问题文本
    
    def _validate_answer(self, answer: str, question: str) -> bool:
        """
        验证生成的回答是否有效
        
        Args:
            answer: 生成的回答文本
            question: 原问题文本
            
        Returns:
            bool: 回答是否有效
        """
        # 检查回答长度
        if not answer or len(answer) < 10:
            return False
        
        # 检查回答是否包含违禁词
        forbidden_words = ["骂人", "脏话", "投诉"]
        for word in forbidden_words:
            if word in answer:
                return False
        
        # 可以添加更多验证规则
        
        return True
    
    def _fill_answer(self, answer: str) -> bool:
        """
        将回答填入文本框
        
        Args:
            answer: 回答文本
            
        Returns:
            bool: 填写操作是否成功
        """
        try:
            textarea = self.browser.find_element_by_xpath("//textarea[contains(@class, 'answer-input')]")
            textarea.clear()
            textarea.send_keys(answer)
            logger.info("成功填写回答")
            return True
        except Exception as e:
            logger.error(f"填写回答失败: {e}")
            return False
    
    def _get_timestamp(self) -> str:
        """
        获取当前时间戳
        
        Returns:
            str: 格式化的时间戳
        """
        from datetime import datetime
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S") 